/*! \file MemoryMappedFile.h
 *	\brief <write description for MemoryMappedFile.h>
 *
 *	created:	2010/11/23
 *	created:	23:11:2010   10:12
 *	filename: 	C:\src\tactics-engine\libs\io\MemoryMappedFile.h
 *	file path:	C:\src\tactics-engine\libs\io
 *	file base:	MemoryMappedFile
 *	file ext:	h
 *	author:		Vitalii Trubchaninov
 *				vitalii.trubchaninov@ubisoft.com
 */

#ifndef _io_MEMORYMAPPEDFILE_UNIX_H_
#define _io_MEMORYMAPPEDFILE_UNIX_H_

#pragma once

#include <fcntl.h>

#include "core/String.h"
#include "io/MemoryMappedFileTypes.h"
#include "utils/unix/FileHandle.h"

namespace tt{
namespace io{

namespace impl{

class MemoryMappedHandle
{
public:
	MemoryMappedHandle();
	MemoryMappedHandle(void* data, Size size);
	~MemoryMappedHandle();

	void Reset();
	void Swap(MemoryMappedHandle&);

	const void* GetData() const;
	Size GetSize() const;

	Bool Valid() const;
	operator bool() const;

private:
	void* m_Data;
	Size m_Size;
};

} //namespace impl

class MemoryMappedFilePS
{
public:
	explicit MemoryMappedFilePS();
	explicit MemoryMappedFilePS(const std::wstring& fileMappingName);
	~MemoryMappedFilePS();

	bool Open(const std::wstring& fileName, MemoryMappedFileMode mode);
	void Close();

	bool Writeable() const;

	Size GetSize() const;
	const void* GetData() const;

private:
	bool Open();
	bool Create();

	static Size GetFileSize(const utils::FileHandle& file);
	static Size GetFileSize(const std::wstring& fileName);

	UInt desireAccessFile() const;
	UInt shareModeMapping() const;
	UInt desireAccessMapping() const;
	UInt protectMapping() const;

private:
	StringW m_FileMappingName;
	StringW m_FileName;
	MemoryMappedFileMode m_Mode;
	utils::FileHandle m_File;
	impl::MemoryMappedHandle m_Data;
};

} //namespace io
} //namespace tt
#include "io/unix/MemoryMappedFile_unix.inl"

#endif //_io_MEMORYMAPPEDFILE_UNIX_H_